package cn.lnexin.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;

/**
 * 接收激活数据
 * 
 * @Description:TODO
 * @author Daniel
 * @date 2018年1月17日 下午4:44:09
 */
public class ReceiveActiveHandler extends ChannelInboundHandlerAdapter {
	
	private AsciiString contentType = HttpHeaderValues.TEXT_PLAIN;
	
	static String res = "{\"ret\":\"ok\"}";
	
	private HttpRequest request;
	
	
	static int count = 0;
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
		if (msg instanceof HttpRequest) {
			request = (HttpRequest) msg;
			String uri = request.getUri();
			System.out.println("Uri:" + uri);
			count++;
			System.out.println(count);
		}
		
		if (msg instanceof HttpHeaders) {
			HttpHeaders headers = (HttpHeaders) msg;
//			headers.
		}
		if (msg instanceof HttpContent) {
			HttpContent content = (HttpContent) msg;
			ByteBuf buf = content.content();
			System.out.println(buf.toString(CharsetUtil.UTF_8));
			buf.release();
			
			FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(res.getBytes())); // 2
			HttpHeaders heads = response.headers();
			heads.add(HttpHeaderNames.CONTENT_TYPE, contentType + "; charset=UTF-8");
			heads.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); // 3
			heads.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
			ctx.write(response);
			ctx.flush();
		}
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
		ctx.flush(); // 4
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		if (null != cause) cause.printStackTrace();
		if (null != ctx) ctx.close();
	}
	
}
